﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using JCPogi.Core.Helpers;

namespace JCPogi.Core {

    //TODO: refactor this into SequentialDeviceCommandContext (abstract)
    public class SendSmsCommandContext : DeviceCommandContext {        

        public SendSmsCommandContext(string recipient, string message, CommunicationDevice device) : base(device) {
            _recipient = recipient;
            _message = message;
        }

        public override DeviceCommandResult PerformCommand(PerformCommandContext context) {
            foreach (var command in GetCommandSequence()) {
                var response = Device.Execute(command);
                if (response.Type != command.ExpectedResponse) {
                    // stop here. Return an invalid result
                    return new DeviceCommandResult { ErrorMessage = response.Buffer };
                }
            }

            return DeviceCommandResult.Successful;
        }

        protected virtual IEnumerable<DeviceCommand> GetCommandSequence() {
            yield return new DeviceCommand {
                CommandText = "AT"
            };
            yield return new DeviceCommand {
                CommandText = "AT+CSCS=\"IRA\""
            };
            yield return new DeviceCommand { 
                CommandText = "AT+CMGF=1" 
            };
            yield return new DeviceCommand { 
                CommandText = "AT+CMGS=\"{0}\"".WithTokens(_recipient),
                ExpectedResponse = DeviceCommandResponseType.MessagePrompt,                
            };
            yield return new DeviceCommand {
                CommandText = "{0}{1}{2}".WithTokens(_message, char.ConvertFromUtf32(26), "\r")
            };
        }

        private readonly string _recipient;
        private readonly string _message;
    }
}
